const express = require('express')
const userTable = require('../../db/user/userTable')
const userDetailTable = require('../../db/user/userDetailTable')
const blogTable = require('../../db/blog/blogTable')

const authorizationApp = express()

/**
 * 鉴权接口 鉴定用户有无令牌
 */

authorizationApp.get('/', async (req, res) => {
  // 查询当前用户有没有令牌 且为过审和非冻结状态
  const rs = await userTable.findOne({
    token: req.headers.authorization,
    freezed: false
  })

  let [status, message] = rs ? [200, 'yes'] : [403, 'no']

  if (status !== 200) {
    res.send({ status, message })
  } else {
    // 如果用户有 token 则查询用户详情表 返回对应的详情信息
    let userDetails = await userDetailTable.findOne({
      key: rs.key
    }, {
      _id: false,
      __v: false,
      key: false
    })

    // 计算用户所有文章被阅览和被点赞的数量
    let userBlogs = await blogTable.find(
      { author_id: rs._id }
    )

    let viewsTotal = userBlogs.reduce((total, blog) => total + blog.views, 0)
    let likesTotal = userBlogs.reduce((total, blog) => total + blog.likes, 0)

    // 返回用户的详细信息
    res.send({
      status,
      message,
      data: {
        userData: {
          userId: rs._id,
          userName: rs.userName,
          avatar: rs.avatar,
          isAdmin: rs.isAdmin,
          superAdmin: rs.superAdmin,
          approved: rs.approved,
          freezed: rs.freezed,
          introduction: rs.introduction,
          userDetails,
          viewsTotal,
          likesTotal
        }
      }
    })
  }
})

module.exports = authorizationApp